package com.binguo.api.service.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binguo.socket.SocketService;
import com.binguo.socket.service.MenJinSocketService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import java.util.Base64;
import java.util.List;

@Component
public class RedisSubscriber extends MessageListenerAdapter {

    @Autowired
    private MenJinSocketService menJinSocketService;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String sendMsg = message.toString();
        sendMsg = sendMsg.substring(1, sendMsg.length() - 1);
        JSONObject sendParam = JSON.parseObject(new String(Base64.getDecoder().decode(sendMsg)));
        if (sendParam.containsKey("isBinding")) {
            Integer deskId = sendParam.getInteger("deskId");
            Integer shopId = sendParam.getInteger("shopId");
            List<Integer> customerIdList = menJinSocketService.createBindingFace(shopId,deskId);
            if (customerIdList != null){
                sendParam = menJinSocketService.createPersonFace(shopId,deskId,customerIdList,1);
                if (sendParam != null) {
                    Integer logId = sendParam.getInteger("id");
                    SocketService.sendtoUser(sendParam.toJSONString(), deskId.toString(), logId);
                }
            }
        }else {
            String deskId = sendParam.getInteger("deskId").toString();
            logger.info("deskId:"+deskId);
            sendParam.remove("deskId");
            Integer logId = sendParam.getInteger("id");
            logger.info("logId:"+logId);
            if (SocketService.socketSet.get(deskId) != null) {
                logger.info("发送消息");
                SocketService.sendtoUser(sendParam.toJSONString(), deskId, logId);
                logger.info("发送消息完成");
            }
        }
    }
}